import { Request } from 'express';
import querystring from 'querystring';
import crypto from 'crypto';
import * as configParam from "../../app/app.config";
import { WxpayPaymentResult, WxpayOrder } from "./wxpay.interface";

/**
 * 签名参数
 */
const wxpayKey = configParam.WXPAY_KEY;

/**
 * 微信支付：签名
 */
export const wxpaySign = (
  data: WxpayOrder | WxpayPaymentResult,
  key: string,
) => {
  // 1. 排序
  const sortedData = Object.keys(data)
    .sort()
    .reduce((accumulator, key) => {
      accumulator[key] = data[key];
      return accumulator;
    }, {});

  // 2. 转换成地址查询符
  const stringData = querystring.stringify(sortedData, null, null, {
    encodeURIComponent: querystring.unescape,
  });

  // 3. 结尾加上密钥
  const stringDataWithKey = `${stringData}&key=${key}`;

  // 4. md5 后全部大写
  const sign = crypto
    .createHash('md5')
    .update(stringDataWithKey)
    .digest('hex')
    .toUpperCase();

  return sign;
};


/**
 * 微信支付：验证支付结果通知
 */
export const wxpayVerifyPaymentResult = async (
  paymentResult: WxpayPaymentResult,
) => {
  const { sign } = paymentResult;
  delete paymentResult['sign'];

  const selfSign = wxpaySign(paymentResult, wxpayKey);

  const isValidSign = sign === selfSign;

  return isValidSign;
};
